package com.think.cloud.thinkshop.mall.service.uv;

import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.think.cloud.thinkshop.mall.domain.uv.UVRecord;
import com.think.cloud.thinkshop.mall.mapper.uv.UVRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class AppUVServiceImpl implements AppUVService{
    @Autowired
    private UVRecordMapper uvRecordMapper;
    @Override
    public void record(HttpServletRequest request) {
        String clientIP = ServletUtil.getClientIP(request);
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        UVRecord uvRecord = uvRecordMapper.selectOne(Wrappers.<UVRecord>lambdaQuery()
                .eq(UVRecord::getIp, clientIP)
                .eq(UVRecord::getRecordDay, date)
        );
        if (uvRecord ==null){
            uvRecordMapper.insert( UVRecord.builder().ip(clientIP).recordDay(date).build());
        }
    }

    @Override
    public double getRecordTotal(String startTime, String endTime) {
        return uvRecordMapper.selectCount(Wrappers.<UVRecord>lambdaQuery()
                .gt(UVRecord::getCreateTime,startTime)
                .le(UVRecord::getCreateTime,endTime)
        );
    }
}
